package com.dlkj.threadPool.core.encrypt;

import com.dlkj.threadPool.utils.AESEncryptUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.xml.internal.ws.client.sei.ResponseBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Author : lei
 * @Company ：DiLang Technology
 * @Date : 2019/1/12 9:46
 * @Description : 对返回数据加密
 **/
@ControllerAdvice(basePackages = "com.dlkj.threadPool.controller")
public class EncodeResponseAdvice implements ResponseBodyAdvice {

    private static final Logger LOGGER = LoggerFactory.getLogger(EncodeResponseAdvice.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        boolean encode = false;
        if (methodParameter.getMethod().isAnnotationPresent(SecurityParameter.class)) {
            // 获取注解配置的包含和去除字段
            SecurityParameter serializedField = methodParameter.getMethodAnnotation(SecurityParameter.class);
            // 出参是否需要加密
            encode = serializedField.outEncode();
        }
        if (encode) {
            LOGGER.info("对方法method:[" + methodParameter.getMethod().getName() + "]数据进行加密");
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(o);
                return AESEncryptUtil.encrypt(result);
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.error("对方法method:[" + methodParameter.getMethod().getName() + "]数据进行解密时异常：" + e.getMessage());
            }
        }
        return o;
    }
}
